<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\KolManage;

use App\Models\Basics\SysCountry;
use App\Models\Basics\SysICountry;
use App\Models\Basics\SysPlat;
use App\Models\Basics\SysPlatCountry;
use App\Models\CustomerDelivery\CustomerOrder;
use App\Models\CustomerDelivery\CustomerOrderDetails;
use App\Models\KolManage\Kol;
use App\Models\KolManage\KolOrder;
use App\Models\KolManage\KolSku;
use App\Models\Product\ProductSku;
use App\Models\Sys\Logs;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;

class KolOrderAjax
{

    /**
     * 查看收货详情
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function viewDetail($id){
        $customerOrder = CustomerOrder::query()->findOrFail($id);
        return view('customer-delivery.delivery-demand.modal-detail', compact('customerOrder'));
    }

    /**
     * 创建消费者订单 (手动,添加订单(自建))
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function createCustomerOrderKol($param){

        $receiver = $param['receiver'];
        $detail = $param['detail'];
        $kol = $param['kol'];

        try{
            $email = $kol['email'];
            $orderChannel = $param['order_channel'];
            $orderType = $param['order_type'];
            $platId = $param['plat_id'];
            $countryId = $param['country_id'];

            if(!$email) {
                return response()->json(['status' => false, 'message' => 'kol红人邮箱不能为空']);
            }

            if(!$orderChannel || !$orderType || !isset($platId) || !$countryId){
                return response()->json(['status' => false, 'message' => '订单参数必选,不能为空']);
            }

            //生成国内自建订单号（KOL）
            $orderNo = $param['order_no'] ?? '';
            if (!$orderNo) {
                $orderNoStr = KolOrder::query()->max('order_no');
                $orderNoNumber = (substr($orderNoStr, -6) + 1); //截取订单标识字母后6位的数字（整数）,加一
                $orderNo = getKolOrderNo($orderNoNumber);
            }

            $orderCount = CustomerOrder::query()->where(['order_no'=>$orderNo])->count();
            if($orderCount > 0) {
                return response()->json(['status' => false, 'message' => '订单号已存在, 请重新选择单号']);
            }

            //获取国家
            $countryObj = SysCountry::getModelById($countryId);
            if(empty($countryObj)) return response()->json(['status' => false, 'message' => '发货国家异常!']);
            //获取国家对应的发货站点
            $areaId = SysCountry::getAreaIdByCountryId($countryObj->id);
            if(empty($areaId)) return response()->json(['status' => false, 'message' => '发货站点异常!']);

            $kolArray = Kol::query()->get()->pluck('kol_code')->toArray();
            $kolNumber = (substr(max($kolArray), -6) + 1); //截取客户标识字母后的数字（整数）,加一
            $kolCode = getKolNo($kolNumber);

            //验证订单明细，并组装明细
            $orderDetailData = [];
            $kolSku = [];
            foreach($detail as $item) {
                $count = CustomerOrderDetails::query()
                    ->where('order_no', $orderNo)
                    ->where('psku_id', $item['psku_id'])
                    ->count();
                if($count > 0) break;

                $orderDetailData[] = [
                    'psku_id'   => $item['psku_id'],
                    'plat_sku'  => CustomerOrderDetails::getOrderPlatsku($orderNo, $item['psku_id']),
                    'order_num' => intval($item['apply_num']) ?? 0,
                    'status'    => CustomerOrderDetails::ORDER_DELIVERY_NO, //订单申请状态 (1:未申请发货)
                ];

                $productSku = ProductSku::query()->find($item['psku_id']);
                $kolSku[] = [
                    'kol_code'    => $kolCode,
                    'classify_id' => $productSku->classify_id,
                    'psku_id'     => $item['psku_id'],
                    'admin_id'    => Admin::user()->id
                ];
            }
            if(empty($orderDetailData)) return response()->json(['status' => false, 'message' => '产品不能为空,请添加产品!']);

            DB::beginTransaction();
            //收货人信息
            $receiverData = [
                'country'   => $receiver['country'],
                'receiver'  => $receiver['receiver'],
                'address'   => $receiver['address'],
                'state'     => $receiver['state'],
                'city'      => $receiver['city'],
                'postcode'  => $receiver['postcode'],
                'phone'     => $receiver['phone'],
            ];

            ////创建相关订单信息
            //$orderObj = CustomerOrder::query()->create([
            //    'order_no'      => $orderNo,
            //    'order_at'      => date('Y-m-d H:i:s', time()),
            //    'order_channel' => $orderChannel,   //订单渠道(1.C端，2.B端)
            //    'order_type'    => $orderType,  //订单类型(1.订单，2.寄样)
            //    'plat_id'       => $platId,  //订单平台 (0:无 1:FBA亚马逊 2:shopify 3:乐天)
            //    'country_id'    => $countryObj->id,  //发货国家
            //    'country_code'  => $countryObj->country,  //发货国家编码
            //    'area_id'       => $areaId,  //发货站点
            //]);
            //$orderObj->receiver()->create($receiverData);
            //$orderObj->detail()->createMany($orderDetailData);
            //if(!$orderObj) throw new \Exception('订单录入失败!');
            //Logs::logs('customer-order', "创建消费订单(自建KOL)：{$orderNo}", $orderObj->id);

            //创建kol
            Kol::query()->where('email', $email)->firstOrCreate(
                ['email' => $email],
                [
                    'kol_code'        => $kolCode,
                    'name'            => $kol['kol_name'],
                    'mobile'          => $kol['kol_mobile'],
                    'address'         => $kol['kol_address'],
                    'media_account'   => $kol['media_account'],
                    'media_platform'  => $kol['media_platform'],
                    'media_zone'      => $kol['media_zone'],
                    'media_follower'  => $kol['media_follower'],
                    'media_style'     => $kol['media_style'],
                    'area_id'         => $kol['kol_area_id'],
                    'country_id'      => $kol['kol_country_id'],
                    'admin_id'        => Admin::user()->id,
                ]
            );

            foreach ($kolSku as $k => $v){
                KolSku::query()->create([
                    'kol_code' => $v['kol_code'],
                    'classify_id' => $v['classify_id'],
                    'psku_id' => $v['psku_id'],
                    'admin_id' => Admin::user()->id,
                ]);
            }

            //创建kol订单
            $kolOrderObj = KolOrder::query()->create([
                'kol_code' => $kolCode,
                'order_no' => $orderNo,
                'admin_id' => Admin::user()->id,
            ]);
            if(!$kolOrderObj) throw new \Exception('KOL订单录入失败!');

            DB::commit();
            return response()->json(['status' =>true, 'message' => '操作成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

}
